<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/10
 * Time: 11:15
 */

namespace app\admin\controller;


use app\reuse\controller\ResponseJson;
use app\service\jobService;
use Redis\Redis;
use think\Db;

class TransactionData extends Common
{
    use ResponseJson;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 历史交易-K线统计
     */
    function historicalTransactions()
    {
        # 历史交易
        $info = Db::table('trad_audit')->field('count(id) value,date(trad_time) time')
            ->where('trad_status != 1 and is_violations=1')
            ->group('date(trad_time)')
            ->order('trad_time asc')
            ->select();
        $dailyTime = array_column($info, 'time');
        $start = date("Y-m-d", strtotime("-1 month", strtotime(end($dailyTime))));
        if ($start < $dailyTime[0]) {
            $start = $dailyTime[0];
        }
        $end = end($dailyTime);
        if (empty($info)) {
            $info = array(array('time' => date('Y-m-d'), 'value' => 0));
            $dailyTime = array_column($info, 'time');
            $start = date('Y-m-d');
            $end = date('Y-m-d');
        }
        $this->assign('dailyData', implode(',', array_column($info, 'value')));
        $this->assign('dailyTime', implode(',', (array_map('change_to_quotes', $dailyTime))));
        $this->assign('startTime', $start);
        $this->assign('endTime', $end);
        return $this->fetch('/transactionData/historicalTransactions');
    }

    /**
     * @return mixed|string
     * @throws \think\exception\DbException
     * @content 待匹配数据分析-各等级比例列表
     */
    function proportionToBeSold()
    {
        if (input('get.action') == 'view') {
            # 待匹配数分析
            /**总体占比*/
            # 当前出售生意数量
            $currentSales = Db::table('member_business')->where('status=3 and lanunch=1')->count();
            # 需购买玩家数量
            $needBuy = Db::table('member_business_grid mbg,member m,team t')
                ->where('mbg.status in (1,3) and mbg.member_business_id = 0 
                and mbg.member_code = m.code and m.team_id = t.id and m.fictitious!=1')
                ->count();
            $this->assign('currentSales', $currentSales);
            $this->assign('needBuy', $needBuy);
            /**各等级比例列表*/
            return $this->fetch('/transactionData/proportionToBeSold');
        }
        if (input('get.action') == 'ajax') {
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 20;
            }
            $_where = '';
            # 搜索条件
            $searchParams = json_decode(input('post.searchParams'), true);
            if (!empty($searchParams)) {
                if (!empty($searchParams['search'])) {
                    # 团队名称/领导人手机号
                    $_where = " and title like '%" . $searchParams['search'] . "%'";
                }
                if (!empty($searchParams['min'])) {
                    # 周期-基础价值
                    $_where .= " and id in (select distinct industry_id from industry_cycleincome where min_num >= " . $searchParams['min'] . ")";
                }
                if (!empty($searchParams['max'])) {
                    # 周期-最高价值
                    $_where .= " and id in (select distinct industry_id from industry_cycleincome where max_num <= " . $searchParams['max'] . ")";
                }
                if (!empty($searchParams['min_income'])) {
                    # 收益-最小值
                    $_where .= " and id in (select distinct industry_id from industry_cycleincome where (min_num*day_income) >= " . $searchParams['min_income'] . ")";
                }
                if (!empty($searchParams['max_income'])) {
                    # 收益-最大值
                    $_where .= " and id in (select distinct industry_id from industry_cycleincome where (min_num*day_income) <= " . $searchParams['max_income'] . ")";
                }
            }
            # 各等级比例列表
            $info = Db::table('industry ind')
                ->field('id,title,level,min_worth,max_worth,
                (select count(mb.id) from member_business mb,member m,team t where earnings_level=ind.level and mb.status in (1,2,4)  and m.code=mb.member_code and t.id = m.team_id) forSale,
                (select count(mb.id) from member_business mb,member m where earnings_level=ind.level and mb.status = 3 and m.code=mb.member_code and mb.lanunch=1) selling
                ')
                ->where('is_del = 2 and status = 1' . $_where)
                ->group('level')
                ->select();
            $level_section=matchingLevelCommon();
            foreach($info as $k=>$v){
                # 查询当前等级 可匹配哪些用户等级
                $_canUseLevel=array();
                for($i=0;$i<count($level_section);$i++){
                    if(in_array($v['level'],$level_section[$i])){
                        array_push($_canUseLevel,$i+1);
                    }
                }

                # 查询这些等级的用户有多少人 生意空栏位有多少个
                $info[$k]['needToBuy']=Db::table("member_business_grid mbg,member m,team t")
                    ->where("mbg.status=1 or mbg.status=3")
                    ->where("mbg.member_business_id=0 and mbg.member_code=m.code and m.level in (".implode(',',$_canUseLevel).") and m.team_id = t.id and m.fictitious!=1")
                    ->count();
                # 查询正在匹配中的生意栏位有多少个
                $info[$k]['matching']=Db::table("member_business_grid mbg,member m,team t")
                    ->where("mbg.status=4")
                    ->where("mbg.member_business_id=0 and mbg.member_code=m.code and m.level in (".implode(',',$_canUseLevel).") and m.team_id = t.id and m.fictitious!=1")
                    ->count();
                $info[$k]["canuselevel"]=implode(',',$_canUseLevel);
            }
            return $this->jsonSuccessData($info);
        }

        if (input('get.action') == 'detailView') {
            # 详情页面
            $this->assign('level', input('get.level'));
            $this->assign('canuselevel',input("get.canuselevel"));
            $this->assign('title',input("get.title"));
            $this->assign('industry_id',input("get.industry_id"));
            $this->assign('min_worth',input("get.min_worth"));
            $this->assign('max_worth',input("get.max_worth"));

            return $this->fetch('transactionData/proportionToBeSoldDetail');
        }
        if (input('get.action') == 'detail') {
            # 详情数据
            # 查看详情(按团队分组)
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            # 接收可匹配等级
            $canuselevel=input("get.canuselevel");
            $title=input("get.title");
            $industry_id=input("get.industry_id");
            $min_worth=input("get.min_worth");
            $max_worth=input("get.max_worth");
            # 接收等级
            $level = input('post.level');
            $_where = '';
            # 搜索条件
            $searchParams = json_decode(input('post.searchParams'), true);
            if (!empty($searchParams)) {
                # 团队名称/领导人手机号
                $_where = " and (t.id = (select from member m where m.phone like '%".$searchParams['search']."%') or t.title like '%" . $searchParams['search'] . "%')";
            }
            $info=Db::table("team t")
                ->field("t.id,t.title,'{$title}' as industry_title,'{$industry_id}' as industry_id,'{$min_worth}' as min_worth,'{$max_worth}' as max_worth,
                    (select count(mbg.id) from member_business_grid mbg,member m where mbg.member_business_id=0 
                and mbg.member_code=m.code and  mbg.status in (1,3) and m.level in ({$canuselevel}) and m.team_id=t.id ) needToBuy
               
                ")
                ->where("t.is_fake=1 ".$_where)
                ->paginate($listRows, false, ['query' => request()->param()]);

            $info=json_decode(json_encode($info),true);
            $_redis=new Redis();
            foreach($info['data'] as $k=>$v){
               // (select count(mb.id) from member_business mb,member m where mb.earnings_level={$level} and mb.status = 2 and mb.member_code=m.code and m.team_id = t.id) forSale,
               // (select count(mb.id) from member_business mb,member m where mb.earnings_level={$level} and mb.status = 3 and mb.member_code=m.code and m.team_id = t.id) selling
                # 待出售
                $forSale=Db::table("industry_cycleincome IC")
                    ->field("IC.min_num,IC.max_num,(select count(mb.id) from member_business mb,member m
                     where mb.earnings_level={$level} and mb.industry_id = {$industry_id} and m.code=mb.member_code and m.team_id={$v['id']} and mb.status in (1,2,4)
                     and ((IC.max_num<{$max_worth} and mb.sale_price>=IC.min_num and mb.sale_price<IC.max_num)
                     or (IC.max_num={$max_worth}) and ((mb.sale_price>=IC.min_num and mb.sale_price<IC.max_num) or (mb.sale_price>=IC.max_num)))) num")
                    ->where(array("IC.industry_id"=>$industry_id))
                    ->select();
                $info['data'][$k]['forSale']=$forSale;
                # 出售中
                $selling=Db::table("industry_cycleincome IC")
                    ->field("IC.min_num,IC.max_num,(select count(mb.id) from member_business mb,member m
                     where mb.earnings_level={$level} and mb.industry_id = {$industry_id} and m.code=mb.member_code and m.team_id={$v['id']} and mb.status = 3 and mb.lanunch=1
                     and ((IC.max_num<{$max_worth} and mb.sale_price>=IC.min_num and mb.sale_price<IC.max_num)
                     or (IC.max_num={$max_worth}) and ((mb.sale_price>=IC.min_num and mb.sale_price<IC.max_num) or (mb.sale_price>=IC.max_num)))) num")
                    ->where(array("IC.industry_id"=>$industry_id))
                    ->select();
                $info['data'][$k]['selling']=$selling;
                # 匹配中数量
                $value_section=$_redis->hGet("team".$v['id']."level".$level);
                if(empty($value_section)){
                    $value_section=array();
                }
                $info['data'][$k]['value_section']=$value_section;
            }
            # 获取当前生意等级可匹配的人

            return $this->jsonSuccessData($info);
        }
    }

    /**
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 投放行业
     */
    function launchIndustry()
    {
        if (input('get.action') != 'ajax') {
            # 接收用户信息
            $memberInfo = json_decode(urldecode(input('get.memberInfo')), true);
            # 等级
            $level = input('get.level');
            $this->assign('info', $memberInfo);
            $this->assign('level', $level);
            $this->assign('industry_id', input("get.industry_id"));
            $this->assign('industry_title', input("get.industry_title"));
            $this->assign('min_worth',input("get.min_worth"));
            $this->assign('max_worth',input("get.max_worth"));
            return $this->fetch('/transactionData/launchIndustry');
        } else {
            # 投放行业
            $info = input('post.');
            # 查询行业详情
            $industryInfo = Db::table('industry')
                ->field('title,logo,level')
                ->where(array('id' => $info['industry_id']))
                ->find();
            # 判断行业的周期 , 周期收益
            $industry = Db::table('industry_cycleincome')
                ->field('cycle_period,day_income,min_num,max_num')
                ->where("industry_id = " . $info['industry_id'] .
                    " and min_num <= " . $info['earnings_price'] . " and max_num >= " . $info['earnings_price'])
                ->find();
            if(empty($info["team_id"])){
                # 默认所有团队
                $team = Db::table('team')
                    ->field('group_concat(id) team_id')
                    ->where("is_fake=1")
                    ->select();
                $info["team_id"]=$team['team_id'];
            }
            $_array=array(
                'member_code' => $info['code'],
                'industry_id' => $info['industry_id'],
                'industry_imgurl' => $industryInfo['logo'],
                'industry_title' => $industryInfo['title'],
                'day_income' => $industry['day_income'] * $info['earnings_price'],
                'status' => 3,
                'buy_time' => date("Y-m-d H:i:s"),
                'growth_cycle' => $industry['cycle_period'],
                'earnings_ratio' => $industry['day_income'],
                'earnings_price' => $info['earnings_price'],
                'earnings_level' => $industryInfo['level'],
                'buy_price' => $info['earnings_price'],
                'sale_price'=>$info['earnings_price'],
                'team_id' => $info['team_id'],
                'sell_time' => date('Y-m-d H:i:s'),
                'place_status'=>2,
                'day_rents'=>floatval($industry['day_income']*$info['earnings_price']*$industry['day_rent']),
                'rent_day'=>$industry['cycle_period'],
                'plurs_grid'=>$info['plurs_grid'], // 需剩余多少栏位才能匹配这个生意
                'precedence'=>$info['precedence'], //  是否优先的状态 1.优先 2.不优先
                'lanunch'=>2                            // 是否为投放行业
            );
            $businessId = Db::table('member_business')->insertGetId($_array);
            $_array['id']=$businessId;
            $_array['cycle_period']=$industry['cycle_period'];
            $_array['now_day_income']=$industry['day_income'];
            # 查询用户信息
            $memberinfo=Db::table("member")->field("name,phone")->where(array("code"=>$info['code']))->find();
            $_array['sale_member_name']=$memberinfo['name'];
            $_array['sale_member_phone']=$memberinfo['phone'];
            $_redis=new Redis();
            $ware=$_redis->hGetJson("wareHouse",$info['code']);
            if(!empty($ware)){
                array_push($ware,$_array);
                $_redis->hSetJson("wareHouse",$info['code'],$ware);
            }
            # 将用户生意信息存入售卖池中
            $sale_list=$_redis->hGetJson("member_sale_bussiness",$industryInfo['level']);
            if(empty($sale_list)){
                $sale_list=array();
            }
            if($info['precedence']==1){
                # 优先状态
                array_unshift($sale_list,$_array);
            }else{
                array_push($sale_list,$_array);
            }
            array_push($sale_list,$_array);
            $_redis->hSetJson("member_sale_bussiness",$industryInfo['level'],$sale_list);
            return array('status' => true);
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 查找用户信息
     */
    function searchMemberInfo()
    {
        # 用户ID / 手机号
        $searchInfo = input('post.searchInfo');
        if (!empty($searchInfo)) {
            # 根据条件查找用户信息
            $info = Db::table('member m')
                ->field('name,code,phone,wx_number,ali_number,unionpay_number')
                ->leftJoin('member_collection mc', 'mc.member_code=m.code')
                ->where("phone = '" . $searchInfo . "' or code = '" . $searchInfo . "'")
                ->find();
            if (!empty($info)) {
                return array('status' => true, 'msg' => '搜索成功', 'memberInfo' => $info);
            } else {
                return array('status' => false, 'msg' => '搜索结果为空');
            }
        } else {
            return array('status' => false, 'msg' => '搜索条件为空');
        }
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 赠送金币数量
     */
    function giveGold()
    {
        $info = Db::table('log_gold')
            ->field('coalesce(sum(gold_num),0) num')
            ->join('(select 1 as id union 
            select 2 as id union select 3 as id union 
            select 4 as id union select 5 as id union 
            select 6 as id) as typeBranch', 'typeBranch.id=log_gold.type_branch', 'right')
            ->group('typeBranch.id')
            ->order('typeBranch.id asc')
            ->select();
        $this->assign('data', implode(',', array_column($info, 'num')));
        $this->assign('countNum', array_sum(array_column($info, 'num')));
        return $this->fetch('/transactionData/giveGold');
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 赠送积分数量
     */
    function giveIntegral()
    {
        $info = Db::table('log_integral')
            ->field('coalesce(sum(num),0) num')
            ->join('(select 1 as id union 
            select 2 as id union select 3 as id union 
            select 4 as id union select 5 as id union 
            select 6 as id) as typeBranch', 'typeBranch.id=log_integral.type_branch', 'right')
            ->group('typeBranch.id')
            ->order('typeBranch.id asc')
            ->select();
        $this->assign('data', implode(',', array_column($info, 'num')));
        $this->assign('countNum', array_sum(array_column($info, 'num')));
        return $this->fetch('/transactionData/giveIntegral');
    }

    /**
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @context 批量投放行业
     */
    function bentch_lanunch()
    {
        if(input("get.active")!="ajax"){
            $level=input('get.level');
            $section=getCanUseValueSectionCommon($level);
            $_return=array();
            $_redis=new Redis();
            foreach ($section as $k=>$v){
                $num=$_redis->hGet(strval($level),$v[0]."and".$v[1]);
                if(empty($num)){
                    $num=0;
                }
                array_push($_return,array("section"=>$v,"num"=>$num));
            }
            $this->assign('section',$_return);
            $this->assign('canuselevel',input("get.canuselevel"));
            $this->assign('title',input("get.title"));
            $this->assign('industry_id',input("get.industry_id"));
            $this->assign('min_worth',input("get.min_worth"));
            $this->assign('max_worth',input("get.max_worth"));
            return $this->fetch('/transactionData/bentch_lanunch');
        }else{
            $param=input("post.");
            # 查看价格是否在价值区间内
            foreach($param['earnings_price'] as $k=>$v){
                if($v<$param['min_worth'] or $v>$param['max_worth']){
                    return array("status"=>false,"msg"=>"请输入区间内有效价值");
                }
            }
            $_industry_info=getsIndustryDetail($param['industry_id']);
            $_redis=new Redis();
            # 添加用户生意
            foreach($param['member_code'] as $k=>$v){
                if($param['lanunch_num'][$k]>0){
                    # 判断当前价值处于哪个阶段
                    $day_income_prop=0;
                    $cycle_period=0;
                    if($param['earnings_price'][$k]>=$param['max_worth']){
                        $end=end($_industry_info['cycleIncome']);
                        $day_income_prop=$end['day_income'];
                        $cycle_period=$end['cycle_period'];
                    }else{
                        foreach($_industry_info['cycleIncome'] as $ck=>$cv){
                            if($cv['min_num']<=$param['earnings_price'][$k] and $param['earnings_price'][$k]<$cv['max_num']){
                                $day_income_prop=$cv['day_income'];
                                $cycle_period=$cv['cycle_period'];
                                break;
                            }
                        }
                    }
                    # 判断团队id
                    if(empty($param["team_id"][$k])){
                        # 默认所有团队
                        $team = Db::table('team')
                            ->field('group_concat(id) team_id')
                            ->where("is_fake=1")
                            ->select();
                        $team_id=$team['team_id'];
                    }else{
                        # 团队去重复
                       $team_id=implode(',',array_unique(explode(',',$param["team_id"][$k])));
                    }

                    for($i=0;$i<$param['lanunch_num'][$k];$i++){
                        $_array=array(
                            "member_code"=>$v,
                            "industry_id"=>$param['industry_id'],
                            "industry_imgurl"=>$_industry_info['info']['logo'],
                            "industry_title"=>$_industry_info['info']['title'],
                            "day_income"=>priceFormat($day_income_prop*$param['earnings_price'][$k]/$cycle_period),
                            "sale_price"=>$param['earnings_price'][$k],
                            "status"=>3,
                            "buy_time"=>date("Y-m-d H:i:s"),
                            "growth_cycle"=>$cycle_period,
                            "earnings_ratio"=>$day_income_prop,
                            "earnings_price"=>$param['earnings_price'][$k],
                            "earnings_level"=>$_industry_info['info']['level'],
                            "buy_price"=>$param['earnings_price'][$k],
                            "team_id"=>$team_id,
                            "sell_time"=>date("Y-m-d H:i:s"),
                            "place_status"=>2,
                            "day_rents"=>priceFormat($day_income_prop*$param['earnings_price'][$k]/$cycle_period*$_industry_info['info']['day_rent']),
                            "rent_day"=>$cycle_period,
                            'plurs_grid'=>$param['plurs_grid'][$k], // 需剩余多少栏位才能匹配这个生意
                            'precedence'=>$param['precedence'][$k], //  是否优先的状态 1.优先 2.不优先
                            'lanunch'=>2                            // 是否为投放行业
                        );
                        $businessId=Db::table("member_business")->insertGetId($_array);
                        $_array['id']=$businessId;
                        $_array['cycle_period']=$cycle_period;
                        $_array['now_day_income']=$day_income_prop;
                        $_array['sale_member_name']=$param['name'][$k];
                        $_array['sale_member_phone']=$param['phone'][$k];

                        # 放入仓库缓存
                        $ware=$_redis->hGetJson("wareHouse",$v);
                        if(!empty($ware)){
                            array_push($ware,$_array);
                            $_redis->hSetJson("wareHouse",$v,$ware);
                        }
                        # 判断是否优先状态
                        $sale_list=$_redis->hGetJson("member_sale_bussiness",$_industry_info['info']['level']);
                        if(empty($sale_list)){
                            $sale_list=array();
                        }
                        if($param['precedence'][$k]==1){
                            # 优先状态
                            array_unshift($sale_list,$_array);
                        }else{
                            array_push($sale_list,$_array);
                        }
                        $_redis->hSetJson("member_sale_bussiness",$_industry_info['info']['level'],$sale_list);
                    }
                }
            }
            return array("status"=>true);
        }
    }

    /**
     * @return mixed
     * @context 选择团队
     */
    function choose_team()
    {
        $id=input("get.id");
        $this->assign("id",$id);
        return $this->fetch('/transactionData/chooseTeam');
    }

    function lanunch_list()
    {
        if(input("get.action")!='ajax'){
            # 今日投放交易额
            $today=Db::table("member_business mb")
                ->join("trad_audit ta","ta.industry_id=mb.id and ta.complaint=1 and ta.trad_status in (2,3)")
                ->where(array("mb.status"=>-1,"mb.lanunch"=>2))
                ->where("date(buy_time)='".date("Y-m-d")."'")
                ->sum("mb.sale_price");
            if(empty($today)){
                $today=0;
            }
            $this->assign("today",$today);
            # 昨日投放交易额
            $yestoday=Db::table("member_business mb")
                ->join("trad_audit ta","ta.industry_id=mb.id and ta.complaint=1 and ta.trad_status in (2,3)")
                ->where(array("mb.status"=>-1,"mb.lanunch"=>2))
                ->where("date(buy_time)='".date("Y-m-d",strtotime("-1 day"))."'")
                ->sum("mb.sale_price");
            if(empty($yestoday)){
                $yestoday=0;
            }
            $this->assign("yestoday",$yestoday);
            # 查询所有行业
            $industry=Db::table("industry")->field("id,level,title")->where(array("category"=>1,"status"=>1))->select();
            $this->assign("industry",$industry);
            return $this->fetch("/transactionData/lanunch_list");
        }else{
            $where="mb.lanunch=2 ";
            # 手机号昵称ID搜索
            $search=input("post.search");
            if(!empty($search)){
                $where.=" and (m.phone = '".$search."' or m.name='".$search."' or m.code='".$search."')";
            }
            # 行业筛选
            $industryId=input("post.industryId");
            if(!empty($industryId)){
                $where.=" and mb.industry_id={$industryId}";
            }
            # 行业价值区间筛选
            $min=input("post.min");
            $max=input("post.max");
            if(!empty($min)){
                $where.= " and mb.sale_price>={$min} and mb.sale_price<={$max}";
            }
            # 优先等级筛选
            $precedence=input("post.precedence");
            if(!empty($precedence)){
                $where.=" and mb.precedence={$precedence}";
            }
            # 匹配要求筛选 空几个
            $plurs_grid=input("post.plurs_grid");
            if(!empty($plurs_grid)||strlen($plurs_grid)>0){
                $where.=" and mb.plurs_grid={$plurs_grid}";
            }
            # 状态筛选
            $status=input("post.status");
            if(empty($status)){
                $status=1;
            }
            if($status==1){
                $where.=" and mb.status in (-1,7) and mb.settlement_status=1";
            }elseif($status==2){
                $where.=" and mb.status in (2,3,8,9) and mb.settlement_status=1";
            }else{
                $where.=" and mb.settlement_status=2";
            }
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            $list=Db::table("member_business mb")
                ->field("m.name,m.phone,m.code,
                (select count(t.id) from team t where t.id in (select group_concat(mbs.team_id) from member_business mbs where mbs.member_code = mb.member_code and mbs.lanunch=2 and mbs.settlement_status!=3)) teamCount,
                (select count(mbs.id) from member_business mbs where mbs.member_code=mb.member_code and mbs.status in (2,3,8,9) and mbs.settlement_status=1 and mbs.lanunch=2) waitCount,
                (select convert(coalesce(sum(mbs.sale_price),0),decimal(10,2)) from member_business mbs where mbs.member_code=mb.member_code and mbs.status in (2,3,8,9) and mbs.settlement_status=1 and mbs.lanunch=2) waitPrice,
                (select count(mbs.id) from member_business mbs where mbs.member_code=mb.member_code and mbs.status in (-1) and mbs.lanunch=2 and mbs.settlement_status!=3) alreadyCount,
                (select convert(coalesce(sum(mbs.sale_price),0),decimal(10,2)) from member_business mbs where mbs.member_code=mb.member_code and mbs.status in (-1) and mbs.lanunch=2 and mbs.settlement_status!=3) alreadyPrice,
                (select convert(coalesce(sum(mbs.sale_price),0),decimal(10,2)) from member_business mbs where mbs.member_code=mb.member_code and mbs.status in (-1) and mbs.settlement_status=1 and mbs.lanunch=2) settlementPrice
                ")
                ->join("member m","m.code=mb.member_code")
                ->where($where)
                ->group("mb.member_code")
                ->order("mb.buy_time desc")
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($list);
        }
    }

    function changeSection(){
        $level=input("post.level");
        return array("section"=>getCanUseValueSectionCommon($level));
    }
    function lanunch_detail()
    {
        if(input("get.action")!="ajax"){
            $code=input("get.code");
            $this->assign("code",$code);
            return $this->fetch("/transactionData/lanunch_detail");
        }else{
            $code=input("get.code");
            $where="mb.id > 0 ";
            $status=input("post.status");
            if(!empty($status)){
                switch($status){
                    case 1:
                        $where.=" and mb.status = -1";
                        break;
                    case 2 :
                        $where.= " and mb.status=3";
                        break;
                    case 3 :
                        $where.= " and mb.status=7";
                        break;
                }
            }
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            $list=Db::table("member_business mb")
                ->field("m.name,m.phone,mb.industry_title,
                (select group_concat(t.title) from team t where t.id in (mb.team_id)) team_title,
                mb.sale_price,mb.growth_cycle,mb.earnings_ratio,if(mb.precedence=1,'优先','不优先') precedence_title,
                if(mb.plurs_grid=0,'全部',mb.plurs_grid) plurs_grid,mb.status,mb.settlement_status,mb.id")
                ->join("member m","m.code=mb.member_code")
                ->where(array("mb.member_code"=>$code,"lanunch"=>2,"settlement_status"=>1))
                ->where($where)
                ->order("buy_time desc")
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($list);
        }
    }

    function settlementNow()
    {
        $id=input("post.id");
        Db::table("member_business")->where(array("id"=>$id))->update(array("settlement_status"=>2));
        return array("status"=>true);
    }

    function deleteBusiness()
    {
        $id=input("post.id");
        $info=Db::table("member_business")->where(array("id"=>$id))->find();
        $_redis=new Redis();
        if($info['status']!=-1){
            # 删除售卖中信息
            $sale_list=$_redis->hGetJson("member_sale_bussiness",$info['earnings_level']);
            if(!empty($sale_list)){
                foreach($sale_list as $k=>$v){
                    if($v['id']==$id){
                        unset($sale_list[$k]);
                        break;
                    }
                }
                $_redis->hSetJson("member_sale_bussiness",$info['earnings_level'],array_values($sale_list));
            }
    }
        # 删除用户生意  （后台删除状态改为3）
        Db::table("member_business")->where(array("id"=>$id))->update(array("status"=>-1,"settlement_status"=>3));
        # 删除用户仓库缓存
        $_redis->hDel("wareHouse",$info['member_code']);
        return array("status"=>true);
    }

    function lanunch_write()
    {
        if(input("action")!='ajax'){
            $id=input("get.id");
            $info=Db::table("member_business mb")
                ->field("mb.*,m.name,m.phone,(select group_concat(t.title) from team t where t.id in (mb.team_id)) team_title")
                ->join("member m","m.code=mb.member_code")
                ->where(array("mb.id"=>$id))->find();
            $this->assign('info',$info);
            return $this->fetch("/transactionData/lanunch_write");
        }else{
            $id=input("post.id");
            $precedence=input("post.precedence");
            $plurs_grid=input("post.plurs_grid");
            $level=input("post.level");
            Db::table("member_business")->where(array("id"=>$id))->update(array("precedence"=>$precedence,"plurs_grid"=>$plurs_grid));
            $_redis=new Redis();
            $sale_list=$_redis->hGetJson("member_sale_bussiness",$level);
            if(!empty($sale_list)){
                $_is_continue=false;
                foreach($sale_list as $k=>$v){
                    if($v['id']==$id){
                        $sale_list[$k]['precedence']=$precedence;
                        $sale_list[$k]['plurs_grid']=$plurs_grid;
                        $_is_continue=true;
                        break;
                    }
                }
                $_redis->hSetJson("member_sale_bussiness",$level,array_values($sale_list));
            }
            return array("status"=>true);
        }
    }

    function lanunch_sale()
    {
        if(input("get.action")!=='ajax'){
            $mark=input("get.mark");
            $this->assign("mark",$mark);
            return $this->fetch("/transactionData/lanunch_sale");
        }else{
            $date=date("Y-m-d");
            $search=input("post.search");
            if(!empty($search)){
                $date=$search;
            }else{
                $mark=input("get.mark");
                if($mark=='today'){
                    $date=date("Y-m-d");
                }else{
                    $date=date("Y-m-d",strtotime("-1 day"));
                }
            }
            $where="date(mb.buy_time)='".$date."'";
            # 定义listRows
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            $list=Db::table("member_business mb")
                ->field("m.name,m.phone,mb.industry_title,
                (select group_concat(t.title) from team t where t.id in (mb.team_id)) team_title,
                mb.sale_price,mb.growth_cycle,mb.earnings_ratio,if(mb.precedence=1,'优先','不优先') precedence_title,
                if(mb.plurs_grid=0,'全部',mb.plurs_grid) plurs_grid,mb.status,mb.settlement_status,mb.id")
                ->join("member m","m.code=mb.member_code")
                ->join("trad_audit ta","ta.industry_id=mb.id and ta.complaint=1 and ta.trad_status in (2,3)")
                ->where(array("mb.status"=>-1,"mb.lanunch"=>2))
                ->where($where)
                ->paginate($listRows, false, ['query' => request()->param()]);
            return $this->jsonSuccessData($list);
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @context 投放管理查看详情 确认交易
     */
    function confirmtrade(){
        $id=input("post.id"); // 玩家生意id
        $data = Db::table("trad_audit")->where(array("industry_id" => $id, "is_violations" => 1, "trad_status" => 1))->find();
        if (!empty($data)) {
            $data['sell_id'] = $id;
            $jobService = new jobService();
            $res = $jobService->successTrade($data);
            if ($res['status']) {
                return array("status" => true);
            } else {
                return array("status" => false, "交易失败");
            }
        } else {
            return array("status" => false, "msg" => "该生意不可交易");
        }
    }
}